<?php

namespace App\Http\Controllers\Admin;

use App\Blocks\AdminUserBlock;
use App\Http\Controllers\Controller;
use App\Http\Requests\AdminLogin;
use App\Libs\ResponseMessage;
use App\Models\AdminPermissionRole;
use App\Models\AdminUrls;
use App\Models\AdminUserPermissions;
use App\Models\AdminUserRoles;
use App\Models\AdminUsers;
use App\Models\AdminRoles;
use App\Models\AdminPermissions;
use http\Env\Response;
use Illuminate\Http\Request;
use DB;


class AdminUserController extends Controller
{

    /**
     * @api {get} /admin/admin/login 管理员登录
     * @apiName adminLogin
     * @apiPrivate
     * @apiGroup 后台
     * @apiVersion 0.0.1
     * @apiDescription 管理员登录
     * @apiParam {String} account 系统
     * @apiParam {String} password 当前版本号
     * @apiSuccessExample {json} 操作成功响应示例
     * {
     *      'status' : 'success',
     *      'failedCode' : '',
     *      'failedMsg' : '',
     *      "data": [
     *      ]
     * }
     * @apiErrorExample {json} 操作失败响应示例
     * {
     *      'status' : 'failed',
     *      'failedCode' : 'ERROR CODE',
     *      'failedMsg' : 'ERROR MSG',
     *      'data'  : []
     * }
     */
    public function login(AdminLogin $request)
    {
        $account = $request->get('account');
        $password = md5($request->get('password'));

        $adminUser = AdminUsers::whereNull('deleted_at')
            ->where('account', $account)
            ->where('password', $password)
            ->first();

        if (!$adminUser) {
            return response()->json(ResponseMessage::getInstance()->failed('LOGIN_FAILED')->response());
        }

        $token = md5('admin_' . $adminUser->id . '_' . time());

        \Cache::put($token, $adminUser, \Config::get('session.lifetime'));

        $cookie = \Cookie::make(\Config::get('session.sq_admin_cookie'), $token, \Config::get('session.lifetime'));

        return response()->json(ResponseMessage::getInstance()->success($adminUser)->response())->withCookie($cookie);
    }

    /**
     * @api {get} /admin/admin/currentUser 获取当前登录的用户信息
     * @apiName adminCurrentUser
     * @apiGroup 后台
     * @apiVersion 0.0.1
     * @apiDescription 获取当前登录的用户信息
     * @apiSuccessExample {json} 操作成功响应示例
     * {
     *      'status' : 'success',
     *      'failedCode' : '',
     *      'failedMsg' : '',
     *      "data": [
     *      ]
     * }
     * @apiErrorExample {json} 操作失败响应示例
     * {
     *      'status' : 'failed',
     *      'failedCode' : 'ERROR CODE',
     *      'failedMsg' : 'ERROR MSG',
     *      'data'  : []
     * }
     */
    public function currentUser()
    {
        global $g_admin_uid;
        $adminUser = AdminUsers::where('id', $g_admin_uid)->first();
        return response()->json(ResponseMessage::getInstance()->success($adminUser)->response());
    }

    /**
     * @api {get} /admin/testadmin/Admlist 后台管理员列表
     * @apiName Admlist
     * @apiGroup 后台
     * @apiVersion 0.0.1
     * @apiDescription 后台用户列表
     * @apiSuccessExample {json} 操作成功响应示例
     * {
     *      'status' : 'success',
     *      'failedCode' : '',
     *      'failedMsg' : '',
     *      "data": [
     *      ]
     * }
     * @apiErrorExample {json} 操作失败响应示例
     * {
     *      'status' : 'failed',
     *      'failedCode' : 'ERROR CODE',
     *      'failedMsg' : 'ERROR MSG',
     *      'data'  : []
     * }
     */
    public function adminUserList()
    {
        $roles_data = AdminRoles::select('id', 'name')->whereNull('deleted_at')->get();
        $list = AdminUsers::select('id as key', 'name', 'account', 'password', 'permissions', 'roles', 'created_at')->whereNull('deleted_at')->get();
        $list = json_decode(json_encode($list), true);
        $list_data = [];
        foreach ($list as $key => $value) {
            $list_data[$key]['key'] = $value['key'];
            $list_data[$key]['name'] = $value['name'];
            $list_data[$key]['account'] = $value['account'];
            $list_data[$key]['password'] = $value['password'];
            $list_data[$key]['created_at'] = $value['created_at'];
            $list_data[$key]['permissions'] = explode(',', $value['permissions']);
            $list_data[$key]['roles'] = explode(',', $value['roles']);
        }
        $per_data = AdminPermissions::select('id as key', 'pid', 'name')->whereNull('deleted_at')->get();
        if($per_data){
            $per_data = $this->Admin_tree_data($per_data);
        }

        $data = array(
            'list' => $list_data,
            'pagination' => array(
                'total' => 5,
                'page' => 1,
                'pagesize' => 5,
            ),
            'roles_data' => $roles_data,
            'per_data' => $per_data,
        );
        return response()->json(ResponseMessage::getInstance()->success($data)->response());
    }

    /**
     * @api {get} /admin/authority/Admlist 添加管理员账号
     * @apiName Admlist
     * @apiGroup 后台
     * @apiVersion 0.0.1
     * @apiDescription 添加管理员账号
     * @apiParam {String} account   账号
     * @apiParam {String} password  密码
     * @apiParam {Number} cid       角色ID
     * @apiSuccessExample {json} 操作成功响应示例
     * {
     *      'status' : 'success',
     *      'failedCode' : '',
     *      'failedMsg' : '',
     *      "data": [
     *      ]
     * }
     * @apiErrorExample {json} 操作失败响应示例
     * {
     *      'status' : 'failed',
     *      'failedCode' : 'ERROR CODE',
     *      'failedMsg' : 'ERROR MSG',
     *      'data'  : []
     * }
     */
    public function adminUserAdd(Request $request)
    {
        $validation = \Validator::make($request->all(), [
            'name' => 'required',
            'account' => 'required',
            'password' => 'required'
        ], [
            'name.required' => '必须填写名称',
            'password.required' => '必须填写密码',
            'account.required' => '必须填写账号',
        ]);

        if ($validation->fails()) {
            return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
        }
        $adminUserModel = new AdminUsers();
        $AdminUserPermissionsModel = new AdminUserPermissions();
        $AdminUserRolesModel = new AdminUserRoles();
        $save['account'] = trim($request->post('account'));
        $save['password'] = trim($request->post('password'));
        $save['permissions'] = implode(',', $request->post('permissions'));
        $save['roles'] = implode(',', $request->post('roles'));
        $save['name'] = trim($request->post('name'));
        $save['created_at'] = date('Y-m-d H:i:s', time());
        $save['salt'] = 1024;

        DB::beginTransaction();
        try {
            $save_id = DB::table($adminUserModel->getTable())->insertGetId($save);
            if (!$save_id) {
                DB::rollBack();
                return false;
            }

            if ($save['roles'] != '') {
                $rid = explode(',', $save['roles']);
                $rid_data = array();
                $r = 0;
                foreach ($rid as $value) {
                    $rid_data[$r]['uid'] = $save_id;
                    $rid_data[$r]['rid'] = $value;
                    $r++;
                }
                $Roles_res = DB::table($AdminUserRolesModel->getTable())->insert($rid_data);
                if (!$Roles_res) {
                    DB::rollBack();
                    return false;
                }
            }

            if ($save['permissions'] != '') {
                $pid = explode(',', $save['permissions']);
                $pid_data = array();
                $p = 0;
                foreach ($pid as $value) {
                    $pid_data[$p]['uid'] = $save_id;
                    $pid_data[$p]['pid'] = $value;
                    $p++;
                }
                $per_res = DB::table($AdminUserPermissionsModel->getTable())->insert($pid_data);
                if (!$per_res) {
                    DB::rollBack();
                    return false;
                }
            }


            DB::commit();
            return response()->json(ResponseMessage::getInstance()->success()->response());
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::error($exception);
            return response()->json(ResponseMessage::getInstance()->failed()->response());
        }


    }

    //账号修改
    public function adminUserUpdate(Request $request)
    {
        $validation = \Validator::make($request->all(), [
            'key' => 'required',
            'name' => 'required',
            'account' => 'required',
            'password' => 'required'
        ], [
            'key.required' => '必须选择一位用户',
            'name.required' => '必须填写名称',
            'password.required' => '必须填写密码',
            'account.required' => '必须填写账号',
        ]);

        if ($validation->fails()) {
            return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
        }

        $adminUserModel = new AdminUsers();
        $AdminUserPermissionsModel = new AdminUserPermissions();
        $AdminUserRolesModel = new AdminUserRoles();
        $id = $request->post('key');
        $save['account'] = trim($request->post('account'));
        $save['password'] = trim($request->post('password'));
        $save['permissions'] = implode(',', $request->post('permissions'));
        $save['roles'] = implode(',', $request->post('roles'));
        $save['name'] = trim($request->post('name'));
        DB::beginTransaction();
        try {

            $user_res = DB::table($adminUserModel->getTable())->where('id', $id)->update($save);

            $rol_del = DB::table($AdminUserRolesModel->getTable())->where('uid', $id)->delete();
            if ($save['roles'] != '') {
                $rid = explode(',', $save['roles']);
                $rid_data = array();
                $r = 0;
                foreach ($rid as $value) {
                    $rid_data[$r]['uid'] = $id;
                    $rid_data[$r]['rid'] = $value;
                    $r++;
                }
                $Roles_res = DB::table($AdminUserRolesModel->getTable())->insert($rid_data);
            }


            $per_del = DB::table($AdminUserPermissionsModel->getTable())->where('uid', $id)->delete();

            if ($save['permissions'] != '') {
                $pid = explode(',', $save['permissions']);
                $pid_data = array();
                $p = 0;
                foreach ($pid as $value) {
                    $pid_data[$p]['uid'] = $id;
                    $pid_data[$p]['pid'] = $value;
                    $p++;
                }
                $per_res = DB::table($AdminUserPermissionsModel->getTable())->insert($pid_data);
            }
            if (!$user_res || !$rol_del || !$Roles_res || !$per_del || !$per_res) {
                DB::rollBack();
                return response()->json(ResponseMessage::getInstance()->failed('FAILED')->response());
            } else {
                DB::commit();
                return response()->json(ResponseMessage::getInstance()->success()->response());
            }
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::error($exception);
            return response()->json(ResponseMessage::getInstance()->failed('FAILED')->response());
        }

    }

    //删除管理员
    public function adminUserDel(Request $request)
    {
        $id = $request->post('key');
        if ($request->has('key')) {
            $id = $request->post('key');
            $adminUserModel = new AdminUsers();
            $AdminUserPermissionsModel = new AdminUserPermissions();
            $AdminUserRolesModel = new AdminUserRoles();
            DB::beginTransaction();
            try {
                $user_res = DB::table($adminUserModel->getTable())->where('id', $id)->update(['deleted_at' => date('Y-m-d H:i:s', time())]);
                $roles_res = DB::table($AdminUserRolesModel->getTable())->where('uid', $id)->delete();
                $per_res = DB::table($AdminUserPermissionsModel->getTable())->where('uid', $id)->delete();
                if (!$user_res || !$roles_res || !$per_res) {
                    DB::rollBack();
                    return response()->json(ResponseMessage::getInstance()->failed('FAILED')->response());
                } else {
                    DB::commit();
                    return response()->json(ResponseMessage::getInstance()->success()->response());
                }
            } catch (\Exception $exception) {
                DB::rollBack();
                \Log::error($exception);
                return response()->json(ResponseMessage::getInstance()->failed('FAILED')->response());
            }
        } else {
            return response()->json(ResponseMessage::getInstance()->failed('FAILED')->response());
        }
    }

//    角色列表
    public function adminRolesList()
    {
        $data = AdminRoles::select('id as key', 'name', 'permission')->whereNull('deleted_at')->get();
        $data = json_decode(json_encode($data), true);
        $arr = array();
        foreach ($data as $key => $value) {
            $arr[$key]['key'] = $value['key'];
            $arr[$key]['name'] = $value['name'];
            $arr[$key]['permission'] = explode(',', $value['permission']);
        }
        $res = array(
            'list' => $arr,
            'tree_data' => $this->Admin_roles_per_tree(),
        );
        return response()->json(ResponseMessage::getInstance()->success($res)->response());
    }

    //添加角色
    public function adminRolesAdd(Request $request)
    {
        $roles = new AdminRoles();
        $data['name'] = trim($request->post('name'));
        $data['permission'] = $request->post('permission');
        if ($data['name'] == '' || !is_array($data['permission'])) {
            return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
        }
        $data['permission'] = implode(',', $data['permission']);
        $res = DB::table($roles->getTable())->insert($data);
        if ($res) {
            return response()->json(ResponseMessage::getInstance()->success()->response());
        } else {
            return response()->json(ResponseMessage::getInstance()->failed()->response());
        }
    }

    //修改角色权限
    public function adminRolesUpdate(Request $request)
    {
        if ($request->has('id')) {
            $roles = new AdminRoles();
            $id = $request->post('id');
            $data['name'] = $request->post('name');
            $data['permission'] = $request->post('permission');
            $data['permission'] = implode(',', $data['permission']);
            $arr = array(
                'updated_at' => date('Y-m-d H:i:s', time()),
                'name' => $data['name'],
                'permission' => $data['permission'],
            );
            $res = DB::table($roles->getTable())->where('id', $id)->update($arr);
            if ($res) {
                return response()->json(ResponseMessage::getInstance()->success()->response());
            } else {
                return response()->json(ResponseMessage::getInstance()->failed()->response());
            }
        } else {
            return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
        }

    }

    //角色删除
    public function adminRolesDel(Request $request)
    {
        $roles = new AdminRoles();
        if ($request->has('id')) {
            $id = $request->post('id');

            $res = DB::table($roles->getTable())->where('id', $id)->update(array('deleted_at' => date('Y-m-d H:i:s', time())));
            if ($res) {
                return response()->json(ResponseMessage::getInstance()->success()->response());
            } else {
                return response()->json(ResponseMessage::getInstance()->failed()->response());
            } 
        } else {
            return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
        }
    }

    //权限节点
    public function Admin_roles_per_tree()
    {
        $sql = AdminPermissions::select('id', 'pid', 'name')->whereNull('deleted_at')->get();
        $data = json_decode(json_encode($sql), true);
        $array = array();
        foreach ($data as $key => $value) {
            $array[$key]['title'] = $value['name'];
            $array[$key]['key'] = $value['id'];
            $array[$key]['value'] = $value['id'];
            $array[$key]['pid'] = $value['pid'];
        }

        $items = array();
        foreach ($array as $value) {
            $items[$value['key']] = $value;
        }
        $tree = array();
        foreach ($items as $key => $value) {
            if (isset($items[$value['pid']])) {
                $items[$value['pid']]['children'][] = &$items[$key];
            } else {
                $tree[] = &$items[$key];
            }
        }
        return $tree;
    }

    //权限节点列表
    public function adminPerList()
    {
        $perModel = new AdminPermissions();
        $Url = new AdminUrls();
        $data = DB::table($perModel->getTable())->select('id as key', 'pid', 'name', 'rule')->whereNull('deleted_at')->get();
        if(!$data){
            return Response()->json(ResponseMessage::getInstance()->success()->response());
        }
        $Url_data = DB::table($Url->getTable())->select('id', 'url', 'method')->get();
        $per_data = DB::table($perModel->getTable())->where('pid', 0)->whereNull('deleted_at')->get();
        $data = json_decode(json_encode($data), true);
        foreach ($data as &$value) {
            $value['rule'] = explode(',', $value['rule']);
        }
        $list = $this->Admin_tree_data($data);
        $arr = array(
            'list' => $list,
            'url_data' => $Url_data,
            'per_data' => $per_data,
        );
        return Response()->json(ResponseMessage::getInstance()->success($arr)->response());
    }


    //修改权限节点
    public function adminPerUpdate(Request $request)
    {
        if ($request->has('key')) {
            $per_Model = new AdminPermissions();
            $AdminPerRoleModel = new AdminPermissionRole();
            $id = $request->post('key');
            $data['pid'] = $request->post('pid');
            $data['name'] = trim($request->post('title'));
            $rule = $request->post('uid');
            $data['rule'] = implode(',', $rule);
            $per_res = DB::table($per_Model->getTable())->where('id', $id)->update($data);
            if ($per_res) {
                return response()->json(ResponseMessage::getInstance()->success()->response());
            } else {
                return response()->json(ResponseMessage::getInstance()->failed()->response());
            }

        } else {
            return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
        }
    }


    //删除权限
    public function adminPerDel(Request $request)
    {
        if ($request->has('key')) {
            $AdminPerModel = new AdminPermissions();
            $AdminPerRoleModel = new AdminPermissionRole();
            $id = $request->post('key');
            DB::beginTransaction();
            try{
                $Per_res = DB::table($AdminPerModel->getTable())->where('id', $id)->update(['deleted_at' => date('Y-m-d H:i:s', time())]);
                $Role_res = DB::table($AdminPerRoleModel->getTable())->whereIn('permission_id',$id)->deleted();
                if (!$Per_res || !$Role_res){
                    DB::rollback();
                    return response()->json(ResponseMessage::getInstance()->failed()->response());
                }
                DB::commit();
                return response()->json(ResponseMessage::getInstance()->success()->response());
            }catch (\Exception $exception) {
                DB::rollBack();
                \Log::error($exception);
                return response()->json(ResponseMessage::getInstance()->failed()->response());
            }
        } else {
            return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
        }
    }

    //添加权限
    public function adminPerAdd(Request $request)
    {
        $validation = \Validator::make($request->all(), [
            'title' => 'required',
        ], [
            'title.required' => '必须填写名称',
        ]);
        if ($validation->fails()) {
            return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
        }
        $AdminPerRoleModel = new AdminPermissionRole();
        $AdminPerModel = new AdminPermissions();
        $data['name'] = $request->post('title');
        $data['pid'] = $request->post('pid');
        $rule = [];
        if($request->has('rule')){
            $rule = $request->post('uid');
        }

        $data['rule'] = implode(',', $rule);
        $data['created_at'] = date('Y-m-d H:i:s', time());
        $get_id = DB::table($AdminPerModel->getTable())->insert($data);
        if ($get_id){
            return response()->json(ResponseMessage::getInstance()->success()->response());
        }else{
            return response()->json(ResponseMessage::getInstance()->failed()->response());
        }

    }

    private function Admin_tree_data($data)
    {
        $data = json_decode(json_encode($data), true);
        $array = [];
        foreach ($data as $key => $value) {
            $array[$key]['title'] = $value['name'];
            $array[$key]['key'] = $value['key'] ? $value['key'] : $value['id'];
            $array[$key]['value'] = $value['key'] ? $value['key'] : $value['id'];
            $array[$key]['pid'] = $value['pid'];
            if (isset($value['rule'])) {
                $array[$key]['rule'] = $value['rule'];
            }
        }

        $items = array();
        foreach ($array as $value) {
            $items[$value['key']] = $value;
        }
        $tree = array();
        foreach ($items as $key => $value) {
            if (isset($items[$value['pid']])) {
                $items[$value['pid']]['children'][] = &$items[$key];
            } else {
                $tree[] = &$items[$key];
            }
        }
        return $tree;
    }

    //后台提现列表
    public function userWithdraw(Request $request){
        $page = $request->get('currentPage',1);
        $pageSize = $request->get('pageSize',5);
        
        $AdminModal = new AdminUserBlock();
        $list = $AdminModal->userWithdraw($page,$pageSize);

        return response()->json(ResponseMessage::getInstance()->success($list)-> response());

    }

    public function userWithdrawUpdate(Request $request)
    {
        if (!$request->has('id') || !$request->has('status')) {
            return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
        }
        $data['id'] = $request->post('id');
        $data['status'] = $request->post('status');
        $AdminModal = new AdminUserBlock();
        $result = $AdminModal->userWithdrawUpdate($data);
        // return $result;
        if ($result) {
            return response()->json(ResponseMessage::getInstance()->success()->response());
        }else{
            return response()-> json (ResponseMessage::getInstance()->failed()->response());
        }

    }


}